package com.huobao.yunying.activitys.muyingquan;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huobao.yunying.adapters.TiedetailAdapter;
import com.huobao.yunying.base.HuobaoBaseActivity;
import com.huobao.yunying.entity.CommitReply;
import com.huobao.yunying.entity.QuanziComment;
import com.huobao.yunying.https.Http;
import com.huobao.yunying.https.HttpConst;
import com.huobao.yunying.https.HttpListener;
import com.huobao.yunying.https.HttpUtil;
import com.huobao.yunying.utils.BitmapTools;
import com.huobao.yunying.utils.ImageUtils;
import com.huobao.yunying.utils.ImageUtils.OnImageLoadListener;
import com.huobao.yunying.utils.ShareUtils;
import com.huobao.yunying.utils.SkipUtils;
import com.huobao.yunying.utils.UserUtils;
import com.huobao.yunying.utils.Utils;
import com.huobao.yunying.utils._PopupImageString;
import com.huobao.yunying.views.RoundImageView;
import com.huobao.zhangying.R;
import com.xrz.sxm.base.utils.ScreenUtil;

import net.bither.util.NativeUtil;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.xutils.common.util.LogUtil;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 帖子详情
 * 
 * @author Administrator
 *
 */
public class Act_Tiezi_Detail extends HuobaoBaseActivity
		implements OnClickListener, OnItemClickListener, OnRefreshListener2<ListView> {

	// 底部评论
	@ViewInject(R.id.llyt_pinglun)
	private View llyt_pinglun;
	// 选择图片按钮
	@ViewInject(R.id.btn_select_photo)
	private ImageView btn_select_photo;
	// 输入框
	@ViewInject(R.id.edt_content)
	private EditText edt_content;
	// 发送评论按钮
	@ViewInject(R.id.btn_send_pinglun)
	private TextView btn_send_pinglun;
	/////////////////////// 底部评论结束

	// 顶部
	@ViewInject(R.id.btn_back)
	private ImageView btn_back;
	// 只看楼主
	@ViewInject(R.id.btn_see_who)
	private TextView btn_see_who;
	// 更多
	@ViewInject(R.id.btn_more)
	private ImageView btn_more;
	//////////////////////////// 顶部结束

	////////////////////////////// header
	// 头像
	private RoundImageView img_userphoto;
	// 用户名
	private TextView tv_username;
	// 精热顶
	private TextView tv_jing;
	private TextView tv_re;
	private TextView tv_ding;
	// 标题
	private TextView tv_title;
	// 浏览量
	private TextView tv_seenum;
	// 时间
	private TextView tv_time;
	// 正文
	private TextView tv_content;
	// 赞
	private TextView btn_zan;
	// 评论数
	private TextView tv_pinglunnum;
	// 圈子名
	private TextView tv_quanzi_name;
	// 商品信息
	private RelativeLayout rtly_goods;
	private TextView tv_goods_name;
	private TextView tv_price;
	private ImageView img_goodicon;

	private TextView tv_10;

	// 图片
	private LinearLayout llyt_views;

	//////////////////////////////////////// header over

	private void initHeadview(View headview) {
		img_userphoto = (RoundImageView) headview.findViewById(R.id.img_userphoto);
		tv_username = (TextView) headview.findViewById(R.id.tv_username);
		tv_jing = (TextView) headview.findViewById(R.id.tv_jing);
		tv_re = (TextView) headview.findViewById(R.id.tv_re);
		tv_ding = (TextView) headview.findViewById(R.id.tv_ding);
		tv_title = (TextView) headview.findViewById(R.id.tv_title);
		tv_seenum = (TextView) headview.findViewById(R.id.tv_seenum);
		tv_time = (TextView) headview.findViewById(R.id.tv_time);
		tv_content = (TextView) headview.findViewById(R.id.tv_content);
		btn_zan = (TextView) headview.findViewById(R.id.btn_zan);
		tv_pinglunnum = (TextView) headview.findViewById(R.id.tv_pinglunnum);
		tv_quanzi_name = (TextView) headview.findViewById(R.id.tv_quanzi_name);
		rtly_goods = (RelativeLayout) headview.findViewById(R.id.rtly);
		tv_goods_name = (TextView) headview.findViewById(R.id.tv_goods_name);
		tv_price = (TextView) headview.findViewById(R.id.tv_price);
		img_goodicon = (ImageView) headview.findViewById(R.id.imageview);
		tv_10 = (TextView) headview.findViewById(R.id.tv_10);
		llyt_views = (LinearLayout) headview.findViewById(R.id.llyt_views);
	}

	// 评论列表
	@ViewInject(R.id.listview)
	private PullToRefreshListView pulltorefresh;

	private ListView listview;
	// 帖子id
	private String id;
	// 圈子id
	private String quanziId;
	// 回复评论id
	private String m_ReplyId;
	// 回复评论对象
	private QuanziComment replyComment;

	// 当前页
	private int m_CurrentPage = 1;
	// 排序方式0:升序；1：倒序；
	private int m_Order = 0;
	// 评论选择的图片
	private String mSelectPhoto = null;

	private TiedetailAdapter adapter;
	// private boolean isLoading = false;
	// private View footView;
	// private TextView footMsg;

	private boolean isSeeAll = true;

	private _PopupImageString popUtils;

	@Override
	protected int getContentView() {
		return R.layout.layout_tiezi_detail;
	}

	@Override
	protected String getTitleText() {
		return null;
	}

	@Override
	protected void init() {
		id = getIntent().getStringExtra("id");
		// quanziId = getIntent().getStringExtra("quanziid");
		// if (id == null || quanziId == null) {
		// Toast.makeText(context, "请传完整参数", Toast.LENGTH_SHORT).show();
		// finish();
		// return;
		// }
		listview = pulltorefresh.getRefreshableView();
		pulltorefresh.setMode(Mode.BOTH);
		pulltorefresh.setOnRefreshListener(this);
		View headView = LayoutInflater.from(context).inflate(R.layout.item_tiezi_detail_header, null);
		initHeadview(headView);
		listview.addHeaderView(headView);
		popUtils = new _PopupImageString();
		btn_send_pinglun.setOnClickListener(this);
		btn_zan.setOnClickListener(this);
		// footView =
		// LayoutInflater.from(context).inflate(R.layout.item_footview, null);
		// footMsg = (TextView) footView.findViewById(R.id.tv_message);
		// listview.addFooterView(footView);
		listview.setOnItemClickListener(this);
		adapter = new TiedetailAdapter(context, id);
		listview.setAdapter(adapter);
		btn_back.setOnClickListener(this);
		tv_quanzi_name.setOnClickListener(this);
		btn_select_photo.setOnClickListener(this);
		btn_more.setOnClickListener(this);
		btn_see_who.setOnClickListener(this);
		mAbTitleBar.setVisibility(View.GONE);
		getCommons(true, isSeeAll);
		getTieZiDetail();
		
		EventBus.getDefault().register(this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
	}

	private void showMsg(final FristHostTiezi tiezi) {
		img_userphoto.setRectAdius(90);
		ImageUtils.loadimg(img_userphoto, tiezi.getPortrait());
		tv_username.setText(tiezi.getUser_name());
		tv_jing.setVisibility(tiezi.getIsbetter().equals("1") ? View.VISIBLE : View.GONE);
		tv_re.setVisibility(tiezi.getIshot().equals("1") ? View.VISIBLE : View.GONE);
		tv_ding.setVisibility(tiezi.getIsfirst().equals("1") ? View.VISIBLE : View.GONE);
		tv_title.setText(tiezi.getTitle());
		tv_seenum.setText("浏览数：" + tiezi.getViews());
		tv_time.setText(tiezi.getCreate_time());
		tv_content.setText(tiezi.getContent().replace("\\n", "\n"));
		btn_zan.setText(isParse ? "已赞\n" + tiezi.getFavors() : "赞\n" + tiezi.getFavors());
		tv_pinglunnum.setText("评论数：" + tiezi.getComments());
		tv_quanzi_name.setText(tiezi.getGname() + ">");

		if (TextUtils.isEmpty(tiezi.getGoods_id())) {
			rtly_goods.setVisibility(View.GONE);
		} else {
			rtly_goods.setVisibility(View.VISIBLE);
			tv_goods_name.setText(tiezi.getGoods_name());
			tv_price.setText("￥" + tiezi.getGoods_price());
			ImageUtils.loadimg(img_goodicon, tiezi.getGoods_image());
			rtly_goods.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					SkipUtils.seeDetail(context, tiezi.getGoods_id(), null);
				}
			});
		}

		if (tiezi.getImages() != null && tiezi.getImages().size() != 0) {
			List<String> imgs = tiezi.getImages();
			createImageViews(imgs);
		}
	}

	private void createImageViews(List<String> imgs) {
		llyt_views.removeAllViews();
		for (int i = 0; i < imgs.size(); i++) {
			String path = imgs.get(i);
			ImageView imageview = createImageView(path);
			llyt_views.addView(imageview);
		}
	}

	private ImageView createImageView(String path) {
		final ImageView imview = new ImageView(context);
		ImageUtils.loadimg(imview, path, new OnImageLoadListener() {

			@Override
			public void onLoadSuccess(Drawable drawable) {
				// TODO Auto-generated method stub
				int width = ScreenUtil.getInstant().getDisWidth(context) - 20;
				int hight = width * drawable.getIntrinsicHeight() / drawable.getIntrinsicWidth();
				LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, hight);
				params.topMargin = 3;
				params.bottomMargin = 3;
				imview.setLayoutParams(params);
			}
		});
		return imview;
	}

	// 是否已经点赞了
	private boolean isParse = false;
	// 发帖人id
	private String m_louzhu_id;
	// 分享url
	private String shareUrl;
	// 是否已经收藏
	private boolean isSave = false;

	private void getTieZiDetail() {
		Map<String, String> map = HttpUtil.getParams("app", "posttopic", "id", id);
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				FristHostTiezi tiezi = JSON.parseObject(jsonObject.getString("retval"), FristHostTiezi.class);
				quanziId = tiezi.getGid();
				List<String> images = JSON.parseArray(jsonObject.getJSONObject("retval").getString("images"),
						String.class);
				tiezi.setImages(images);
				shareUrl = tiezi.getUrl();
				isSave = tiezi.getIscollect() == 1;
				m_louzhu_id = tiezi.getUser_id();
				isParse = tiezi.getIsfavor() == 1;
				showMsg(tiezi);
			}

			@Override
			public void onHttpError(String error) {
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.btn_send_pinglun:// 发送评论
			if (m_ReplyId == null)
				sendCommont();
			else
				replyComment();
			new Handler().post(new Runnable() {

				@Override
				public void run() {
					Utils.togSoftkeybord(context, edt_content, true);
				}
			});
			break;
		case R.id.btn_zan:
			parseOrnot(isParse);
			break;
		case R.id.tv_quanzi_name:
			Intent intent = new Intent(this, Act_Quanzi_Detail.class);
			intent.putExtra("id", quanziId);
			startActivity(intent);
			break;
		case R.id.btn_select_photo:
			selectPhoto();
			break;
		case R.id.btn_see_who:
			chose();
			break;
		case R.id.btn_more:
			showPop(v);
			break;
		}
	}

	private void showPop(View v) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map;

		map = new HashMap<String, Object>();
		map.put("text", "分享");
		map.put("image", R.mipmap.fenxiang);
		list.add(map);

		map = new HashMap<String, Object>();
		map.put("text", "收藏");
		map.put("image", R.mipmap.shoucang);
		list.add(map);

		// map = new HashMap<String, Object>();
		// map.put("text", "跳页");
		// map.put("image", R.drawable.tiaoye);
		// list.add(map);

		map = new HashMap<String, Object>();
		map.put("text", m_Order == 1 ? "正序查看" : "倒序查看");
		map.put("image", R.mipmap.daoxu);
		list.add(map);
		popUtils.showPop(context, list, v, new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				popUtils.dismiss();
				switch (position) {
				case 0:
					ShareUtils.showShare(context, shareUrl);
					break;
				case 1:
					if (isSave) {
						Toast.makeText(context, "已经收藏过了", Toast.LENGTH_SHORT).show();
						return;
					}
					saveTiezi();
					break;
				case 2:
					m_CurrentPage = 1;
					m_Order = m_Order == 1 ? 0 : 1;
					// isLoading = false;
					getCommons(true, isSeeAll);
					break;
				}
			}
		});
	}

	protected void saveTiezi() {
		Map<String, String> map = HttpUtil.getParams("app", "posttopic", "act", "collect", "id", id);
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				// TODO Auto-generated method stub
				JSONObject jsonObject = JSON.parseObject(result);
				Toast.makeText(context, jsonObject.getString("retval"), Toast.LENGTH_SHORT).show();
				isSave = true;
			}

			@Override
			public void onHttpError(String error) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void chose() {
		if (isSeeAll) {
			btn_see_who.setText("全部");
			isSeeAll = false;
		} else {
			btn_see_who.setText("只看楼主");
			isSeeAll = true;
		}
		// isLoading = false;
		m_CurrentPage = 1;
		getCommons(true, isSeeAll);
	}

	private void selectPhoto() {
		Intent intent = new Intent(this, MultiImageSelectorActivity.class);
		// 是否显示拍摄图片
		intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
		// 最大可选择图片数量
		intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
		// 选择模式
		intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
		// // 默认选择
		// if(mSelectPath != null && mSelectPath.size()>0){
		// intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST,
		// mSelectPath);
		// }
		startActivityForResult(intent, 1);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1) {
			if (resultCode == RESULT_OK) {
				List<String> mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
				if (mSelectPath != null && mSelectPath.size() != 0) {
					mSelectPhoto = mSelectPath.get(0);
					showSelectPic(mSelectPhoto);
				}
			}
		}
	}

	private void showSelectPic(String mSelectPhoto2) {
		x.image().bind(btn_select_photo, mSelectPhoto2);
	}

	private void parseOrnot(final boolean isCancel) {
		Map<String, String> map = HttpUtil.getParams("app", "posttopic", "act", "favor", "isadd", isCancel ? "0" : "1",
				"id", id);
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				String num = jsonObject.getString("retval");
				btn_zan.setText(isCancel ? "赞\n" + num : "已赞\n" + num);
				isParse = !isCancel;
			}

			@Override
			public void onHttpError(String error) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void sendCommont() {
		String content = edt_content.getText().toString();
		if (TextUtils.isEmpty(content) && mSelectPhoto == null) {
			Toast.makeText(context, "请输入评论内容", Toast.LENGTH_SHORT).show();
			return;
		}
		if (mSelectPhoto != null) {
			uploadPhoto(false);
		} else {
			sendCommont("");
		}

	}

	private void uploadPhoto(final boolean isReply) {
		Bitmap bitmap = BitmapTools.createImageThumbnail(mSelectPhoto);
		if (bitmap == null)
			return;
		File f = new File(mSelectPhoto);
		File newPath = new File(f.getParent(), f.getName() + "temp" + ".jpg");
		NativeUtil.compressBitmap(bitmap, 100, newPath.getAbsolutePath(), true);
		bitmap.recycle();
		String base64str = Base64.encodeToString(Utils.File2byte(newPath.getAbsolutePath()), Base64.NO_WRAP);
		Map<String, String> map = HttpUtil.getParams("app", "uploadpic", "act", "picupload", "type", "8", "user_id",
				UserUtils.getUserid(context) + "", "portrait", base64str);
		Http.getInstant().sendRequest(context, true, HttpConst.UPLOAD_PHOTO_URL, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				String image = jsonObject.getString("retval");
				if (isReply) {
					sendReplyCommit(image);
				} else {
					sendCommont(image);
				}

			}

			@Override
			public void onHttpError(String error) {
				// TODO Auto-generated method stub

			}
		});
	}

	protected void sendReplyCommit(String image) {
		Map<String, String> map = HttpUtil.getParams("app", "postcomment", "act", "replay", "gid", quanziId, "pid", id,
				"id", m_ReplyId, "comment", edt_content.getText().toString(), "images", image);
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				m_CurrentPage = 1;
				edt_content.setText("");
				// isLoading = false;
				getCommons(true, isSeeAll);
				btn_select_photo.setBackgroundResource(R.mipmap.icon_photo);
				btn_select_photo.setImageResource(R.mipmap.icon_photo);
				mSelectPhoto = null;
			}

			@Override
			public void onHttpError(String error) {

			}
		});
	}

	protected void sendCommont(String image) {
		Map<String, String> map = HttpUtil.getParams("app", "postcomment", "act", "publish", "gid", quanziId, "pid", id,
				"comment", edt_content.getText().toString(), "images", image);
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				m_CurrentPage = 1;
				edt_content.setText("");
				// isLoading = false;
				getCommons(true, isSeeAll);
				btn_select_photo.setBackgroundResource(R.mipmap.icon_photo);
				btn_select_photo.setImageResource(R.mipmap.icon_photo);
				mSelectPhoto = null;
			}

			@Override
			public void onHttpError(String error) {

			}
		});
	}

	private void replyComment() {
		String content = edt_content.getText().toString();
		if (TextUtils.isEmpty(content) && mSelectPhoto == null) {
			Toast.makeText(context, "请输入评论内容", Toast.LENGTH_SHORT).show();
			return;
		}
		if (mSelectPhoto != null) {
			uploadPhoto(true);
		} else {
			sendReplyCommit("");
		}

	}

	private void getCommons(final boolean showDialog, final boolean isAll) {
		// isLoading = true;
		Map<String, String> map = HttpUtil.getParams("app", "postcomment", "id", id, "page", m_CurrentPage + "",
				"order", m_Order + "");
		Http.getInstant().sendRequest(context, showDialog, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				JSONArray array = jsonObject.getJSONArray("retval");
				List<QuanziComment> list = new ArrayList<QuanziComment>();
				for (int i = 0; i < array.size(); i++) {
					JSONObject object = array.getJSONObject(i);
					QuanziComment comment = JSON.parseObject(object.toString(), QuanziComment.class);
					JSONArray jsonArray = object.getJSONArray("images");
					if (jsonArray != null) {
						List<String> imgs = JSON.parseArray(jsonArray.toString(), String.class);
						comment.setImages(imgs);
					}

					JSONObject replyObject = object.getJSONObject("reply");
					if (replyObject != null) {
						CommitReply reply = JSON.parseObject(replyObject.toString(), CommitReply.class);
						reply.setImages(JSON.parseArray(replyObject.getString("images"), String.class));
						comment.setReply(reply);
					}
					if (isAll)
						list.add(comment);
					else {
						if (comment.getUser_id().equals(m_louzhu_id)) {
							list.add(comment);
						}
					}
				}
				if (list == null || list.size() == 0) {
//					if (showDialog == false)
//						Toast.makeText(context, "没有更多了！", Toast.LENGTH_SHORT).show();
				}
				if (m_CurrentPage == 1)
					adapter.clear();
				adapter.addAll(list);
				pulltorefresh.onRefreshComplete();
				if(adapter.getCount() == 0){
					adapter.add(new QuanziComment());
				}
			}

			@Override
			public void onHttpError(String error) {
			}
		});
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		LogUtil.e("position="+position);
		if(position < 2)return;
		QuanziComment comment = adapter.getItem(position - 2);
		if(comment == null)return;
		if (comment.getUser_id().equals(String.valueOf(UserUtils.getUserid(context)))) {
			return;
		}
		togKeyBoard(comment);
	}

	@Subscriber(tag = "togKeyBoard")
	public void togKeyBoardByAdapter(QuanziComment comment) {
		togKeyBoard(comment);
	}

	private void togKeyBoard(QuanziComment comment) {
		this.m_ReplyId = comment.getCid();
		this.replyComment = comment;
		edt_content.setHint("回复" + comment.getFloor() + "楼：");
		new Handler().post(new Runnable() {

			@Override
			public void run() {
				Utils.togSoftkeybord(context, edt_content, false);
			}
		});
	}

	// @Override
	// public void onScrollStateChanged(AbsListView view, int scrollState) {
	// // TODO Auto-generated method stub
	//
	// }
	//
	// @Override
	// public void onScroll(AbsListView view, int firstVisibleItem, int
	// visibleItemCount, int totalItemCount) {
	// // TODO Auto-generated method stub
	// if ((firstVisibleItem + visibleItemCount) >= totalItemCount &&
	// totalItemCount != 0) {
	// if (isLoading) {
	// return;
	// }
	// isLoading = true;
	// m_CurrentPage++;
	// getCommons(false, isSeeAll);
	// }
	// }

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		m_CurrentPage = 1;
		getCommons(false, isSeeAll);
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		m_CurrentPage++;
		getCommons(false, isSeeAll);
	}
}
